import api from '@api'
import {
  IS_LOGIN,
  SET_USER_INFO,
  SHOW_TOKEN_ERROR,
  SET_CONFIG
} from '../mutation-types'

import {
  saveToken,
  getToken,
  removeToken,
  cacheUserinfo,
  cacheConfig
} from '@cache'
import cache from '@cache'

const state = {
  isLogin: getToken() ? true : false, // eslint-disable-line
  tokenError: false,
  userinfo: cacheUserinfo.load() || {},
  config: cacheConfig.load() || {}
}

const getters = {
  isLogin (state) {
    return state.isLogin
  },
  tokenError (state) {
    return state.tokenError
  },
  userinfo (state) {
    return state.userinfo
  }
}

const mutations = {
  [IS_LOGIN] (state, data) {
    state.isLogin = data
  },
  [SHOW_TOKEN_ERROR] (state, data) {
    state.tokenError = data
  },
  [SET_USER_INFO] (state, data) {
    state.userinfo = data
  },
  [SET_CONFIG] (state, data) {
    state.config = data
  }
}

const actions = {
  setIsLogin (store, isLogin) {
    store.state.isLogin = isLogin
  },
  /**
   * 登录
   */
  signLogIn (store, params) {
    return api.jpost('login', params)
      .then((res) => {
        if (res.status === 1) {
          saveToken(res.data.token, res.data.expiry)
          store.commit(SET_USER_INFO, res.data)
          store.commit(IS_LOGIN, true)
        }
        return Promise.resolve(res)
      })
      .catch((error) => {
        return Promise.reject(error)
      })
  },
  /**
   * 退出登录
   */
  signOut (store) {
    // api.get("account.logout").then(res=>{

    // })
    removeToken()
    store.commit(IS_LOGIN, false)
    store.commit(SET_USER_INFO, {})
    cache.delete('purview')
    cache.delete('nav')
    localStorage.clear()
  }
}

export default {
  state,
  mutations,
  actions,
  getters
}
